﻿using Mes.Infrastructure.Data.BoundedContext;
using Mes.Infrastructure.Data.BoundedContext.Configurations;
using Mes.Application.Web.AutoFac;
using Microsoft.EntityFrameworkCore;
using FluentValidation;
using System.Reflection;
using Mes.Application.Web.Middlewares;
using Microsoft.OpenApi.Models;
using NLog.Web;
using Mes.Application.AutoMapper;
using Mes.Application.Services.Quartz;

var builder = WebApplication.CreateBuilder(args);
builder.Logging.AddNLog("NLog/Nlog.config");
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true);

builder.Services.AddConfig(builder.Configuration);

builder.Services.AddControllers();

builder.Services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly());

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new OpenApiInfo
    {
        Version = "v1",
        Title = "Mes",
        Description = $"Mes,v1"
    });
    var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename), true);
    var dtoassembly = AppDomain.CurrentDomain.GetAssemblies().Where(x => x.FullName.Contains("Mes.Application.DTO")).FirstOrDefault();
    var dtoFilename = $"{dtoassembly.GetName().Name}.xml";
    options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, dtoFilename), true);
});

// 注册EF，读写数据 业务逻辑方法
builder.Host.UseAutofac();

// 添加 DB 上下文，操作数据库帮助类
builder.Services.AddDbContext<MesDbContext>();

// Mapper 服务注册
builder.Services.EasyAddAutoMapper();

// 定时任务，Quartz 注册
builder.Services.AddQuartzJobService();

builder.Services.AddCors(policy =>
{
    policy.AddPolicy("CorsPolicy", opt => opt
    .AllowAnyOrigin()
    .AllowAnyHeader()
    .AllowAnyMethod()
    .WithExposedHeaders("X-Pagination"));
});

var app = builder.Build();
app.UseMiddleware<GlobalExceptionMiddleware>();

////Auto Migration
//using (var scope = app.Services.CreateScope())
//{
//    var db = scope.ServiceProvider.GetRequiredService<MesDbContext>();
//    db.Database.Migrate();
//}

// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
//{
app.UseSwagger();
app.UseSwaggerUI();
//}

app.UseCors("CorsPolicy");

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();
